package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.domain.AddressBook;
import com.itheima.service.UserAddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author CSY
 * 2022/5/13    20:30
 */
@RestController
@RequestMapping("/addressBook")
@Slf4j
public class AddressBookController {

    @Autowired
    private UserAddressBookService userAddressBookService;
    /**
     * 添加地址的方法
     * @return
     */
    @PostMapping
    public R<AddressBook> addressBooks(@RequestBody AddressBook addressBook){

        AddressBook addressBook1 = userAddressBookService.addAddress(addressBook);

        return addressBook1!=null?R.success(addressBook1):R.error("失败");
    }

    /**
     * 返回地址列表
     * @return
     */
    @GetMapping("/list")
    public R<List<AddressBook>> list(){


        List<AddressBook> allAddress = userAddressBookService.getAllAddress();


        return allAddress!=null?R.success(allAddress):R.error("失败");
    }

    /**
     * 设置默认地址
     * @param addressBook
     * @return
     */
    @PutMapping("/default")
    public R<AddressBook> setdefault(@RequestBody AddressBook addressBook){

        //地址id
        Long id = addressBook.getId();

        AddressBook setdefault = userAddressBookService.setdefault(id);


        return setdefault!=null?R.success(setdefault):R.error("失败");
    }


    /**
     * 返回修改列表地址值
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<AddressBook> updateList(@PathVariable Long id){

        AddressBook address = userAddressBookService.getAddress(id);


        return address!=null ? R.success(address):R.error("失败");
    }

    /**
     * 修改名单
     * @param addressBook
     * @return
     */
    @PutMapping
    public R<String> updateAddress(@RequestBody AddressBook addressBook){


        boolean b = userAddressBookService.updateAddress(addressBook);

        return b?R.success("成功"):R.error("失败");
    }


    /**
     * 删除地址
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam Long ids){


        boolean b = userAddressBookService.deleteAddress(ids);

        return b?R.success("成功"):R.error("失败");

    }


    /**
     * 获取默认地址在订单中
     * @return
     */
    @GetMapping("/default")
    public R<AddressBook> getDefaultAddress(){

        AddressBook defaultAddress = userAddressBookService.getDefaultAddress();

        return defaultAddress!=null?R.success(defaultAddress):R.error("失败");
    }


}
